const orderModel = require('../models/order'); // 导入订单模型
const goodsModel = require('../models/goods');
const orderModel = require('../models/order');
const { pool } = require('../config/db');
const upload = require('../config/upload');

// 创建订单
exports.createOrder = async (req, res) => {
  try {
    // 从请求中获取数据
    const userId = req.user?.id || null;
    const { goods_id, goods_info, quantity = 1 } = req.body || {};
    
    // 参数验证
    if (!userId) {
      return res.status(401).json({ success: false, message: '用户未登录或登录信息无效' });
    }
    
    // 参数验证
    if (!goods_id || !goods_info) {
      return res.status(400).json({ success: false, message: '缺少必要的订单参数' });
    }
    
    // 确保goods_id是整数
    const parsedGoodsId = parseInt(goods_id);
    
    // 验证商品是否存在
    const goods = await goodsModel.getGoodsById(parsedGoodsId);
    
    if (!goods) {
      return res.status(404).json({ success: false, message: '商品不存在' });
    }
    
    // 计算总价
    const total_price = goods.price * quantity;
    
    // 创建订单数据
    const orderData = {
      user_id: userId,
      goods_id: parsedGoodsId,
      goods_info: goods_info,
      total_price: total_price
    };
    
    // 创建订单
    const order = await orderModel.createOrder(orderData);
    
    res.json({
      success: true,
      data: order,
      message: '创建订单成功'
    });
  } catch (error) {
    console.error('创建订单失败:', error);
    res.status(500).json({ success: false, message: '创建订单失败，请稍后重试' });
  }
};

// 获取用户订单列表
exports.getUserOrders = async (req, res) => {
  try {
    // 安全获取用户ID
    const userId = req.user?.id || null;
    const { status, page = 1, pageSize = 10 } = req.query;
    
    // 参数验证
    if (!userId) {
      return res.status(401).json({ success: false, message: '用户未登录或登录信息无效' });
    }
    
    // 安全处理status参数，确保不会传递undefined给SQL
    const safeStatus = status || null;
    
    // 从数据库获取订单列表
    let orders = await orderModel.getUserOrders(userId, safeStatus);
    
    // 为每个订单添加order_no字段
    orders = orders.map(order => ({
      ...order,
      order_no: `ORD${String(order.id).padStart(8, '0')}`
    }));
    
    // 处理分页
    const startIndex = (parseInt(page) - 1) * parseInt(pageSize);
    const endIndex = startIndex + parseInt(pageSize);
    const paginatedOrders = orders.slice(startIndex, endIndex);
    
    res.json({
      success: true,
      data: {
        orders: paginatedOrders,
        total: orders.length,
        page: parseInt(page),
        pageSize: parseInt(pageSize)
      },
      message: '获取订单列表成功'
    });
  } catch (error) {
    console.error('获取订单列表失败:', error);
    res.status(500).json({ success: false, message: '获取订单列表失败，请稍后重试' });
  }
};

// 更新订单状态
exports.updateOrderStatus = async (req, res) => {
  try {
    const userId = req.user?.id || null;
    const { id } = req.params;
    const { status } = req.body;
    
    // 参数验证
    if (!userId) {
      return res.status(401).json({ success: false, message: '用户未登录或登录信息无效' });
    }
    
    if (!status) {
      return res.status(400).json({ success: false, message: '缺少订单状态' });
    }
    
    // 检查订单是否存在且属于当前用户
    const order = await orderModel.getOrderById(parseInt(id));
    if (!order) {
      return res.status(404).json({ success: false, message: '订单不存在' });
    }
    
    if (order.user_id !== userId) {
      return res.status(403).json({ success: false, message: '无权操作该订单' });
    }
    
    // 更新订单状态
    const updatedOrder = await orderModel.updateOrderStatus(parseInt(id), status);
    
    res.json({
      success: true,
      data: updatedOrder
    });
  } catch (error) {
    console.error('更新订单状态失败:', error);
    res.status(500).json({ success: false, message: '更新订单状态失败，请稍后重试' });
  }
};

// 获取订单详情
exports.getOrderDetail = async (req, res) => {
  try {
    const userId = req.user?.id || null;
    const { id } = req.params;
    
    // 参数验证
    if (!userId) {
      return res.status(401).json({ success: false, message: '用户未登录或登录信息无效' });
    }
    
    if (!id) {
      return res.status(400).json({ success: false, message: '缺少订单ID' });
    }
    
    try {
      // 尝试从数据库获取订单详情
      const order = await orderModel.getOrderById(parseInt(id));
      
      if (!order) {
        return res.status(404).json({ success: false, message: '订单不存在' });
      }
      
      // 检查订单是否属于当前用户
      if (order.user_id !== userId) {
        return res.status(403).json({ success: false, message: '无权查看该订单' });
      }
      
      // 为订单添加订单编号
      const orderWithNo = {
        ...order,
        order_no: `ORD${String(order.id).padStart(8, '0')}`,
        goodsInfo: order.goods_info // 确保返回格式与前端期望一致
      };
      
      res.json({
        success: true,
        data: orderWithNo,
        message: '获取订单详情成功'
      });
    } catch (dbError) {
      // 数据库错误处理
      console.error('数据库获取订单详情失败:', dbError);
      return res.status(500).json({ success: false, message: '获取订单详情失败，请稍后重试' });
    }
  } catch (error) {
    console.error('获取订单详情失败:', error);
    res.status(500).json({ success: false, message: '获取订单详情失败，请稍后重试' });
  }
};

// 上传新的订单（支持文件上传）
exports.uploadOrder = async (req, res) => {
  try {
    // 使用upload.single中间件处理单个文件上传
    upload.single('proof_of_payment')(req, res, async (err) => {
      if (err) {
        console.error('文件上传失败:', err);
        return res.status(400).json({ success: false, message: '文件上传失败：' + err.message });
      }
      
      const userId = req.user?.id || null;
      const { goods_id, goods_info, quantity = 1, payment_type = 'alipay' } = req.body;
      
      // 参数验证
      if (!userId) {
        return res.status(401).json({ success: false, message: '用户未登录或登录信息无效' });
      }
      
      // 验证必要参数
      if (!goods_id || !goods_info) {
        return res.status(400).json({ success: false, message: '缺少必要的订单参数' });
      }
      
      try {
        // 验证商品是否存在
        const goods = await goodsModel.getGoodsById(parseInt(goods_id));
        if (!goods) {
          return res.status(404).json({ success: false, message: '商品不存在' });
        }
        
        // 计算总价
        const total_price = goods.price * quantity;
        
        // 解析goods_info参数
        let parsedGoodsInfo = goods_info;
        if (typeof goods_info === 'string') {
          try {
            parsedGoodsInfo = JSON.parse(goods_info);
          } catch (jsonError) {
            return res.status(400).json({ success: false, message: '商品信息格式错误' });
          }
        }
        
        // 创建订单数据
        const orderData = {
          user_id: userId,
          goods_id: parseInt(goods_id),
          goods_info: parsedGoodsInfo,
          total_price
        };
        
        // 如果有上传的支付凭证，添加到订单信息中
        if (req.file) {
          const filePath = '/uploads/' + req.file.filename;
          orderData.payment_proof = filePath;
        }
        
        // 创建订单
        const order = await orderModel.createOrder(orderData);
        
        // 添加支付方式信息
        order.payment_type = payment_type;
        
        res.json({
          success: true,
          data: order,
          message: '订单上传成功'
        });
      } catch (dbError) {
        console.error('数据库创建订单失败:', dbError);
        return res.status(500).json({ success: false, message: '创建订单失败，请稍后重试' });
      }
    });
  } catch (error) {
    console.error('上传订单失败:', error);
    res.status(500).json({ success: false, message: '上传订单失败，请稍后重试' });
  }
};